package com.guang.springbootrequestversion.converter;

import com.guang.springbootrequestversion.bean.Cat;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.util.List;

/**
 * 可以读取，可以写！如果说在参数上加上某个注解，利用消息转换器来进行操作
 *
 * @author liguang
 * @date 2022/5/13 11:29
 */
public class ResolveSelfHttpMessageConverter implements HttpMessageConverter<Cat> {

    /**
     * 将Cat类型能够解析成对应的媒体类型
     *
     * @param clazz
     * @param mediaType
     * @return
     */
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    /**
     * 将Cat类型能够写成对应的媒体类型
     *
     * @param clazz
     * @param mediaType
     * @return
     */
    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return Cat.class.isAssignableFrom(clazz);
    }

    /**
     * 获取支持的内容类型
     *
     * @return
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        // 以这种方式来进行书写！
        return MediaType.parseMediaTypes("application/nb-lig");
        //  return MediaType.parseMediaTypes("parameter-nb-lig");
    }

    /**
     * 读取
     *
     * @param clazz
     * @param inputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    @Override
    public Cat read(Class<? extends Cat> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    /**
     * 写出操作
     *
     * @param cat
     * @param contentType
     * @param outputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    public void write(Cat cat, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        Integer id = cat.getId();
        String name = cat.getName();
        String result = "响应的内容类型是：" + contentType + " 【result】 id=" + id + ";name=" + name;
        // outputMessage.getBody().write(result.getBytes(StandardCharsets.UTF_8));
        outputMessage.getBody().write(result.getBytes());
        // outputMessage.getBody().flush();
    }
}
